namespace Toolbox.Model.Reminder
{
    /// <summary>
    /// 提醒UI组，封装一个提醒项的所有UI组件
    /// </summary>
    public class ReminderUIGroup
    {
        public string ReminderId { get; set; } = "";
        public GroupBox GroupBox { get; set; } = null!;
        public Label NextReminderLabel { get; set; } = null!;
        public Label StatusTextLabel { get; set; } = null!;
        public Label CountdownLabel { get; set; } = null!;
        public TextBox MessageTextBox { get; set; } = null!;
        public Button StartButton { get; set; } = null!;
        public Button ApplyButton { get; set; } = null!;
        public Button TestButton { get; set; } = null!;
        public NumericUpDown IntervalNumeric { get; set; } = null!;
        public ReminderItem ReminderItem { get; set; } = null!;
    }

    public class ReminderPage : BaseTabPage, IDisposable
    {
        /// <summary>
        /// 页签名称
        /// </summary>
        public override string TabName => "提醒";

        /// <summary>
        /// 配置文件名称（不含路径和扩展名）
        /// </summary>
        public override string ConfigFileName => "ReminderConfig";

        /// <summary>
        /// 页签序号（用于排序）
        /// </summary>
        public override int TabOrder => 1;

        // 单个定时器队列
        private System.Timers.Timer _queueTimer = null!;
        private System.Timers.Timer _activityTimer = null!;
        private MainForm _mainForm = null!;

        // UI组列表
        private readonly List<ReminderUIGroup> _reminderUIGroups = [];
        private TextBox _logTextBox = null!;

        // 属性访问器
        public List<ReminderItem> ReminderItems { get; set; } = [];

        public bool IsMonitoring { get; set; }

        public object LockObject { get; } = new();

        // 初始化提醒页面
        public override void InitializePage(TabPage tabPage, MainForm mainForm)
        {
            // 保存主窗口引用
            _mainForm = mainForm;

            // 从配置文件加载提醒设置
            LoadReminderSettings();

            // 主面板
            Panel mainPanel = new Panel { Dock = DockStyle.Fill, Padding = new Padding(20), AutoScroll = true };
            tabPage.Controls.Add(mainPanel);

            // 标题区域
            Label titleLabel = new Label
            {
                Text = "提醒管理",
                Font = new Font("Microsoft YaHei", 16, FontStyle.Bold),
                Location = new Point(10, 10),
                AutoSize = true,
                ForeColor = Color.Green
            };
            mainPanel.Controls.Add(titleLabel);

            // 全部控制按钮（与开始按钮左对齐）
            Button toggleAllButton = new Button
            {
                Text = "全部开始",
                Size = new Size(80, 30),
                Location = new Point(460, 10),
                BackColor = Color.LightGreen,
                UseVisualStyleBackColor = true
            };
            toggleAllButton.Click += (s, e) => ToggleAllMonitoring(mainForm);
            mainPanel.Controls.Add(toggleAllButton);

            // 循环数据直接创建提醒设置组
            int yPosition = 60;
            foreach (ReminderItem reminderItem in ReminderItems)
            {
                ReminderUIGroup uiGroup = CreateReminderUIGroup(mainPanel, reminderItem, yPosition);
                _reminderUIGroups.Add(uiGroup);
                yPosition += 200; // 每个提醒项的高度间隔
            }

            // 日志面板（可调整高度）紧跟提醒设置
            GroupBox logGroup = new GroupBox
            {
                Text = "日志",
                Location = new Point(10, yPosition),
                Size = new Size(530, Math.Max(120, 60)), // 确保最小高度为60像素（3行文本高度）
                Tag = "logGroup" // 用于标识，方便查找
            };
            mainPanel.Controls.Add(logGroup);

            // 调整窗口默认高度，确保完整展示日志区
            mainForm.Size = new Size(530, yPosition + 200);

            _logTextBox = new TextBox
            {
                Multiline = true,
                ScrollBars = ScrollBars.Vertical,
                Location = new Point(10, 20),
                Size = new Size(510, Math.Max(90, 30)), // 确保最小高度为30像素（3行文本高度减去边框）
                ReadOnly = true
            };
            logGroup.Controls.Add(_logTextBox);
            
            // 添加窗口大小改变事件处理，以便调整控件宽度和高度
            tabPage.Resize += (s, e) =>
            {
                // 获取主窗口引用
                MainForm? mainForm = tabPage.FindForm() as MainForm;
                if (mainForm != null)
                {
                    // 调用OnWindowHeightChanged方法调整高度
                    OnWindowHeightChanged(tabPage, mainForm, 0);
                }
                
                // 重新计算控件组宽度，统一使用20像素的左右边距
                int newGroupBoxWidth = mainPanel.Width - 20; // 减去左右边距
                
                // 更新所有控件组的宽度
                foreach (Control control in mainPanel.Controls)
                {
                    if (control is GroupBox groupBox)
                    {
                        groupBox.Width = newGroupBoxWidth;
                        
                        // 更新日志文本框的宽度
                        if (groupBox.Tag?.ToString() == "logGroup")
                        {
                            foreach (Control innerControl in groupBox.Controls)
                            {
                                if (innerControl is TextBox textBox)
                                {
                                    textBox.Width = newGroupBoxWidth - 20; // 减去左右边距
                                }
                            }
                        }
                        // 更新提醒项组内的控件宽度
                        else
                        {
                            foreach (Control innerControl in groupBox.Controls)
                            {
                                if (innerControl is TextBox textBox && textBox.Multiline)
                                {
                                    // 输入框和按钮之间的间隔
                                    textBox.Width = groupBox.Width - 110 - 110;
                                }
                            }
                            
                            // 调整提醒项组内按钮的位置，增加右对齐效果
                            int buttonX = groupBox.Width - 90; // 按钮距离右边缘90像素
                            
                            foreach (Control innerControl in groupBox.Controls)
                            {
                                if (innerControl is Button button)
                                {
                                    // 根据按钮的文本判断是哪个按钮
                                    if (button.Text == "开始" || button.Text == "停止") // StartButton
                                    {
                                        button.Location = new Point(buttonX, 17);
                                    }
                                    else if (button.Text == "生效") // ApplyButton
                                    {
                                        button.Location = new Point(buttonX - 90, 17); // 放在开始按钮左侧
                                    }
                                    else if (button.Location.Y == 95) // TestButton
                                    {
                                        button.Location = new Point(buttonX, 95);
                                    }
                                }
                            }
                        }
                    }
                }
                
                // 调整"全部开始"按钮位置
                foreach (Control control in mainPanel.Controls)
                {
                    if (control is Button button && button.Text.Contains("全部"))
                    {
                        // 找到第一个提醒项的"开始"按钮位置作为参考
                        int startButtonX = 450; // 默认位置
                        if (_reminderUIGroups.Count > 0)
                        {
                            startButtonX = _reminderUIGroups[0].StartButton.Location.X + 10;
                        }
                        button.Location = new Point(startButtonX, 10);
                        break;
                    }
                }
            };
        }

        // 创建单个提醒UI组
        private ReminderUIGroup CreateReminderUIGroup(Panel mainPanel, ReminderItem reminderItem, int yPosition)
        {
            ReminderUIGroup uiGroup = new ReminderUIGroup
            {
                ReminderId = reminderItem.Id,
                ReminderItem = reminderItem,
                // 设置面板
                GroupBox = new GroupBox
                {
                    Text = reminderItem.Name,
                    Location = new Point(10, yPosition),
                    Size = new Size(530, 190)
                }
            };
            mainPanel.Controls.Add(uiGroup.GroupBox);

            // 第一行：提醒间隔设置
            Label intervalLabel = new Label
            {
                Text = "提醒间隔:",
                Location = new Point(20, 20),
                Size = new Size(80, 20),
                TextAlign = ContentAlignment.MiddleRight
            };
            uiGroup.GroupBox.Controls.Add(intervalLabel);

            uiGroup.IntervalNumeric = new NumericUpDown
            {
                Minimum = 1,
                Maximum = 120,
                Value = reminderItem.Interval,
                Location = new Point(110, 20),
                Size = new Size(60, 20)
            };
            uiGroup.IntervalNumeric.ValueChanged += (s, e) =>
            {
                reminderItem.Interval = (int)uiGroup.IntervalNumeric.Value;
                SaveReminderSettings();
                LogMessage(_mainForm, $"{reminderItem.Name}间隔已更新为: {reminderItem.Interval}分钟");
                // 如果当前正在监控，显示立即生效按钮
                if (reminderItem.IsEnabled)
                {
                    uiGroup.ApplyButton.Visible = true;
                }
            };
            uiGroup.GroupBox.Controls.Add(uiGroup.IntervalNumeric);

            Label minuteLabel = new Label
            {
                Text = "分钟",
                Location = new Point(180, 22),
                AutoSize = true
            };
            uiGroup.GroupBox.Controls.Add(minuteLabel);

            uiGroup.ApplyButton = new Button
            {
                Text = "生效",
                Size = new Size(80, 30),
                Location = new Point(350, 17),
                Visible = false // 默认隐藏，开始监控后显示
            };
            uiGroup.ApplyButton.Click += (s, e) =>
            {
                ApplyNewInterval(_mainForm, reminderItem.Id);
                uiGroup.ApplyButton.Visible = false;
            };
            uiGroup.GroupBox.Controls.Add(uiGroup.ApplyButton);

            // 第二行：下次提醒时间、监控状态和剩余时间（一行显示）
            Label nextReminderTextLabel = new Label
            {
                Text = "下次提醒:",
                Location = new Point(20, 45),
                Size = new Size(80, 20),
                TextAlign = ContentAlignment.MiddleRight
            };
            uiGroup.GroupBox.Controls.Add(nextReminderTextLabel);

            uiGroup.NextReminderLabel = new Label
            {
                Text = "未设置",
                ForeColor = Color.Blue,
                Location = new Point(110, 45),
                Size = new Size(100, 20),
                TextAlign = ContentAlignment.MiddleLeft
            };
            uiGroup.GroupBox.Controls.Add(uiGroup.NextReminderLabel);

            // 监控状态标签
            Label statusTextLabel = new Label
            {
                Text = "监控状态:",
                Location = new Point(220, 45),
                Size = new Size(80, 20),
                TextAlign = ContentAlignment.MiddleRight
            };
            uiGroup.GroupBox.Controls.Add(statusTextLabel);

            uiGroup.StatusTextLabel = new Label
            {
                Text = "未启动",
                ForeColor = Color.Red,
                Location = new Point(310, 45),
                Size = new Size(60, 20),
                TextAlign = ContentAlignment.MiddleLeft
            };
            uiGroup.GroupBox.Controls.Add(uiGroup.StatusTextLabel);

            // 剩余时间标签（添加到监控状态后面，同一行）
            Label remainingTimeLabel = new Label
            {
                Text = "剩余时间:",
                Location = new Point(20, 70),
                Size = new Size(80, 20),
                TextAlign = ContentAlignment.MiddleRight
            };
            uiGroup.GroupBox.Controls.Add(remainingTimeLabel);

            uiGroup.CountdownLabel = new Label
            {
                Text = "未开始",
                ForeColor = Color.Blue,
                Location = new Point(110, 70),
                Size = new Size(100, 20),
                TextAlign = ContentAlignment.MiddleLeft
            };
            uiGroup.GroupBox.Controls.Add(uiGroup.CountdownLabel);

            // 提醒内容设置（全宽度，调整位置和大小）
            Label messageLabel = new Label
            {
                Text = "提醒内容:",
                Location = new Point(20, 95),
                Size = new Size(80, 20),
                TextAlign = ContentAlignment.MiddleRight
            };
            uiGroup.GroupBox.Controls.Add(messageLabel);

            uiGroup.MessageTextBox = new TextBox
            {
                Text = reminderItem.Message,
                Multiline = true,
                ScrollBars = ScrollBars.Vertical,
                Location = new Point(110, 95),
                Size = new Size(310, 80), // 减小与按钮的间隔
                Height = 80
            };
            uiGroup.MessageTextBox.TextChanged += (s, e) =>
            {
                reminderItem.Message = uiGroup.MessageTextBox.Text;
                SaveReminderSettings();
            };
            uiGroup.GroupBox.Controls.Add(uiGroup.MessageTextBox);

            uiGroup.TestButton = new Button
            {
                Text = "测试提醒",
                Location = new Point(440, 95),
                Size = new Size(80, 80)
            };
            uiGroup.TestButton.Click += (s, e) => ShowReminder(_mainForm, true, reminderItem.Id);
            uiGroup.GroupBox.Controls.Add(uiGroup.TestButton);

            // 开始按钮
            uiGroup.StartButton = new Button
            {
                Text = reminderItem.IsEnabled ? "停止" : "开始",
                Size = new Size(80, 30),
                Location = new Point(440, 17)
            };
            uiGroup.StartButton.Click += (s, e) => ToggleMonitoring(_mainForm, reminderItem.Id);
            uiGroup.GroupBox.Controls.Add(uiGroup.StartButton);

            // 如果提醒项已启用，更新UI状态
            if (reminderItem.IsEnabled)
            {
                uiGroup.StatusTextLabel.Text = "监控中...";
                uiGroup.StatusTextLabel.ForeColor = Color.Green;
                uiGroup.NextReminderLabel.Text = reminderItem.NextReminderTime.ToString("HH:mm:ss");
                uiGroup.ApplyButton.Visible = true;
            }

            return uiGroup;
        }

        // 加载提醒设置
        private void LoadReminderSettings()
        {
            try
            {
                // 使用新的ReminderConfigManager加载提醒项
                ReminderItems = ReminderConfigManager.Instance.GetReminderItems();

                // 如果没有提醒项，创建默认提醒项
                if (ReminderItems == null || ReminderItems.Count == 0)
                {
                    CreateDefaultReminders();
                }
            }
            catch (Exception ex)
            {
                LogMessage(_mainForm, $"加载提醒设置时发生错误: {ex.Message}");
                ReminderItems = [];
                CreateDefaultReminders();
            }
        }

        // 保存提醒设置
        private void SaveReminderSettings()
        {
            try
            {
                // 使用新的ReminderConfigManager保存提醒项
                ReminderConfigManager.Instance.SaveReminderItems(ReminderItems);
            }
            catch (Exception ex)
            {
                LogMessage(_mainForm, $"保存提醒设置失败: {ex.Message}");
            }
        }

        // 创建默认提醒项
        private void CreateDefaultReminders()
        {
            ReminderItems.Clear();

            // 久坐提醒
            ReminderItems.Add(new ReminderItem
            {
                Id = "sitting",
                Name = "久坐提醒",
                Interval = 45,
                Message = "您已经坐了很长时间了！建议站起来活动一下，看看远处",
                IsEnabled = false,
                NextReminderTime = DateTime.Now.AddMinutes(45)
            });

            // 喝水提醒
            ReminderItems.Add(new ReminderItem
            {
                Id = "water",
                Name = "喝水提醒",
                Interval = 60,
                Message = "该喝水了！保持充足的水分摄入对健康很重要",
                IsEnabled = false,
                NextReminderTime = DateTime.Now.AddMinutes(60)
            });

            // 保存默认设置
            SaveReminderSettings();
        }

        // 处理窗口高度变化的通知 (非静态实现)
        public override void OnWindowHeightChanged(TabPage tabPage, MainForm mainForm, int formHeightChange)
        {
            if (tabPage == null || mainForm == null || _logTextBox == null)
            {
                return;
            }

            // 查找主面板
            Panel? mainPanel = tabPage.Controls.OfType<Panel>().FirstOrDefault();
            if (mainPanel == null)
            {
                return;
            }

            // 查找日志面板
            GroupBox? logGroup = mainPanel.Controls.OfType<GroupBox>()
                .FirstOrDefault(static g => (g.Tag as string) == "logGroup");

            if (logGroup != null)
            {
                // 计算主窗口可用高度（减去标题栏、边框等非客户区高度）
                int clientHeight = mainForm.ClientSize.Height;
                
                // 计算提醒项占用的总高度（标题+按钮+所有提醒项）
                int reminderItemsHeight = 60; // 标题和按钮区域高度
                reminderItemsHeight += _reminderUIGroups.Count * 200; // 每个提醒项高度为200
                
                // 计算日志面板的可用高度
                int availableLogHeight = clientHeight - reminderItemsHeight - 40; // 30为日志面板标题和边距
                
                // 设置最小高度为3行文本的高度（约60像素）加上下边距
                int minLogHeight = 90;
                int newLogHeight = Math.Max(availableLogHeight, minLogHeight);
                
                // 调整日志面板和文本框高度
                logGroup.Size = new Size(logGroup.Width, newLogHeight);
                _logTextBox.Size = new Size(_logTextBox.Width, newLogHeight - 30);
            }
        }

        // 覆盖基类的StopRunning方法，实现资源释放
        public override void StopRunning(MainForm mainForm)
        {
            // 停止队列定时器
            if (_queueTimer != null)
            {
                _queueTimer.Stop();
                _queueTimer.Dispose();
                _queueTimer = null!;
            }

            // 停止活动显示计时器
            if (_activityTimer != null)
            {
                _activityTimer.Stop();
                _activityTimer.Dispose();
                _activityTimer = null!;
            }

            // 调用现有的StopMonitoring方法，保持向后兼容性
            StopMonitoring(mainForm);
        }

        // 开始监控指定的提醒项
        public void StartMonitoring(MainForm mainForm, string reminderId)
        {
            ReminderItem? reminderItem = ReminderItems.Find(r => r.Id == reminderId);
            if (reminderItem == null)
            {
                return;
            }

            ReminderUIGroup? uiGroup = _reminderUIGroups.Find(g => g.ReminderId == reminderId);
            if (uiGroup == null)
            {
                return;
            }

            reminderItem.IsEnabled = true;
            reminderItem.NextReminderTime = DateTime.Now.AddMinutes(reminderItem.Interval);

            // 更新UI
            uiGroup.StartButton.Text = "停止";
            uiGroup.StatusTextLabel.Text = "监控中...";
            uiGroup.StatusTextLabel.ForeColor = Color.Green;

            // 如果队列定时器尚未启动，启动它
            if (_queueTimer == null)
            {
                _queueTimer = new System.Timers.Timer(1000); // 每秒检查一次
                _queueTimer.Elapsed += (sender, e) => ProcessReminderQueue(sender ?? throw new ArgumentNullException(nameof(sender)), e, mainForm);
                _queueTimer.AutoReset = true;
                _queueTimer.Start();
            }

            // 如果活动显示计时器尚未启动，启动它
            if (_activityTimer == null)
            {
                _activityTimer = new System.Timers.Timer(1000);
                _activityTimer.Elapsed += (sender, e) => UpdateActivityDisplay(sender ?? throw new ArgumentNullException(nameof(sender)), e, mainForm);
                _activityTimer.AutoReset = true;
                _activityTimer.Start();
            }

            // 显示生效按钮
            uiGroup.ApplyButton.Visible = true;

            // 保存设置
            SaveReminderSettings();

            LogMessage(mainForm, $"{reminderItem.Name}开始监控，提醒间隔: {reminderItem.Interval}分钟，下次提醒时间: {reminderItem.NextReminderTime:yyyyMMdd HH:mm:ss}");

            // 更新全部控制按钮的状态
            UpdateToggleAllButtonText(mainForm);
        }

        // 切换监控状态
        public void ToggleMonitoring(MainForm mainForm)
        {
            // 这个方法保留用于向后兼容
            if (ReminderItems.Count > 0)
            {
                ToggleMonitoring(mainForm, ReminderItems[0].Id);
            }
        }

        // 切换所有提醒项的监控状态
        public void ToggleAllMonitoring(MainForm mainForm)
        {
            bool anyEnabled = ReminderItems.Any(static r => r.IsEnabled);

            if (anyEnabled)
            {
                // 如果有任何提醒项正在运行，则停止所有
                StopMonitoring(mainForm);
                LogMessage(mainForm, "已停止所有提醒项的监控");
            }
            else
            {
                // 如果没有提醒项在运行，则启动所有
                foreach (ReminderItem reminderItem in ReminderItems)
                {
                    if (!reminderItem.IsEnabled)
                    {
                        StartMonitoring(mainForm, reminderItem.Id);
                    }
                }
                LogMessage(mainForm, "已启动所有提醒项的监控");
            }

            // 更新按钮文本和颜色
            UpdateToggleAllButtonText(mainForm);
        }

        // 更新全部控制按钮的文本和颜色
        private void UpdateToggleAllButtonText(MainForm mainForm)
        {
            // 使用反射获取_mainTabControl字段
            System.Reflection.FieldInfo? mainTabControlField = typeof(MainForm).GetField("_mainTabControl",
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            if (mainTabControlField != null)
            {
                if (mainTabControlField.GetValue(mainForm) is TabControl mainTabControl)
                {
                    TabPage? tabPage = mainTabControl.TabPages.Cast<TabPage>()
                        .FirstOrDefault(static t => t.Text == "提醒");

                    if (tabPage != null)
                    {
                        Panel? mainPanel = tabPage.Controls.OfType<Panel>().FirstOrDefault();
                        if (mainPanel != null)
                        {
                            Button? toggleAllButton = mainPanel.Controls.OfType<Button>()
                                .FirstOrDefault(static b => b.Location.X == 460 && b.Location.Y == 10);

                            if (toggleAllButton != null)
                            {
                                bool anyEnabled = ReminderItems.Any(static r => r.IsEnabled);
                                if (anyEnabled)
                                {
                                    toggleAllButton.Text = "全部停止";
                                    toggleAllButton.BackColor = Color.LightCoral;
                                }
                                else
                                {
                                    toggleAllButton.Text = "全部开始";
                                    toggleAllButton.BackColor = Color.LightGreen;
                                }
                            }
                        }
                    }
                }
            }
        }

        // 切换指定提醒项的监控状态
        public void ToggleMonitoring(MainForm mainForm, string reminderId)
        {
            ReminderItem? reminderItem = ReminderItems.Find(r => r.Id == reminderId);
            if (reminderItem == null)
            {
                return;
            }

            if (reminderItem.IsEnabled)
            {
                StopMonitoring(mainForm, reminderId);
            }
            else
            {
                StartMonitoring(mainForm, reminderId);
            }
        }

        // 停止监控
        public void StopMonitoring(MainForm mainForm)
        {
            // 停止所有提醒项的监控
            foreach (ReminderItem reminderItem in ReminderItems)
            {
                if (reminderItem.IsEnabled)
                {
                    StopMonitoring(mainForm, reminderItem.Id);
                }
            }
        }

        // 停止指定提醒项的监控
        public void StopMonitoring(MainForm mainForm, string reminderId)
        {
            ReminderItem? reminderItem = ReminderItems.Find(r => r.Id == reminderId);
            if (reminderItem == null)
            {
                return;
            }

            ReminderUIGroup? uiGroup = _reminderUIGroups.Find(g => g.ReminderId == reminderId);
            if (uiGroup == null)
            {
                return;
            }

            reminderItem.IsEnabled = false;

            // 更新UI
            uiGroup.StartButton.Text = "开始";
            uiGroup.StatusTextLabel.Text = "已停止";
            uiGroup.StatusTextLabel.ForeColor = Color.Red;
            uiGroup.CountdownLabel.Text = "未开始";
            uiGroup.NextReminderLabel.Text = "--:--:--";

            // 如果没有活动的提醒项，停止队列定时器和活动显示计时器
            if (!ReminderItems.Any(r => r.IsEnabled))
            {
                if (_queueTimer != null)
                {
                    _queueTimer.Stop();
                    _queueTimer.Dispose();
                    _queueTimer = null!;
                }

                if (_activityTimer != null)
                {
                    _activityTimer.Stop();
                    _activityTimer.Dispose();
                    _activityTimer = null!;
                }
            }

            // 隐藏生效按钮
            uiGroup.ApplyButton.Visible = false;

            // 保存设置
            SaveReminderSettings();

            LogMessage(mainForm, $"{reminderItem.Name}已停止监控");

            // 更新全部控制按钮的状态
            UpdateToggleAllButtonText(mainForm);
        }

        // 处理提醒队列
        private void ProcessReminderQueue(object sender, System.Timers.ElapsedEventArgs e, MainForm mainForm)
        {
            if (!ReminderItems.Any(r => r.IsEnabled))
            {
                return;
            }

            lock (LockObject)
            {
                // 获取所有启用的提醒项并按下次提醒时间排序
                List<ReminderItem> enabledReminders = ReminderItems
                    .Where(r => r.IsEnabled)
                    .OrderBy(r => r.NextReminderTime)
                    .ToList();

                // 检查最早到期的提醒
                if (enabledReminders.Count > 0)
                {
                    ReminderItem nextReminder = enabledReminders.First();

                    // 如果当前时间已超过或等于提醒时间，触发提醒
                    if (DateTime.Now >= nextReminder.NextReminderTime)
                    {
                        _ = mainForm.Invoke((MethodInvoker)delegate
                        {
                            ShowReminder(mainForm, false, nextReminder.Id);
                        });
                    }
                }
            }
        }

        // 更新活动显示
        private void UpdateActivityDisplay(object sender, System.Timers.ElapsedEventArgs e, MainForm mainForm)
        {
            if (!ReminderItems.Any(r => r.IsEnabled))
            {
                return;
            }

            _ = mainForm.Invoke((MethodInvoker)delegate
            {
                // 为每个启用的提醒项更新显示
                foreach (ReminderItem? reminderItem in ReminderItems.Where(r => r.IsEnabled))
                {
                    ReminderUIGroup? uiGroup = _reminderUIGroups.Find(g => g.ReminderId == reminderItem.Id);
                    if (uiGroup != null)
                    {
                        // 更新倒计时
                        TimeSpan remaining = reminderItem.NextReminderTime - DateTime.Now;
                        uiGroup.CountdownLabel.Text = remaining.TotalSeconds > 0 ? $"{remaining.Hours:D2}:{remaining.Minutes:D2}:{remaining.Seconds:D2}" : "00:00:00";

                        // 更新下次提醒时间显示
                        uiGroup.NextReminderLabel.Text = reminderItem.NextReminderTime.ToString("HH:mm:ss");
                    }
                }
            });
        }

        // 应用新的提醒间隔
        public void ApplyNewInterval(MainForm mainForm)
        {
            // 这个方法保留用于向后兼容
            if (ReminderItems.Count > 0)
            {
                ApplyNewInterval(mainForm, ReminderItems[0].Id);
            }
        }

        // 应用指定提醒项的新提醒间隔
        public void ApplyNewInterval(MainForm mainForm, string reminderId)
        {
            ReminderItem? reminderItem = ReminderItems.Find(r => r.Id == reminderId);
            if (reminderItem == null)
            {
                return;
            }

            ReminderUIGroup? uiGroup = _reminderUIGroups.Find(g => g.ReminderId == reminderId);
            if (uiGroup == null)
            {
                return;
            }

            reminderItem.NextReminderTime = DateTime.Now.AddMinutes(reminderItem.Interval);

            // 保存设置
            SaveReminderSettings();

            LogMessage(mainForm, $"{reminderItem.Name}提醒间隔已更新为: {reminderItem.Interval}分钟，下次提醒时间: {reminderItem.NextReminderTime:yyyyMMdd HH:mm:ss}");

            // 更新UI显示
            _ = mainForm.Invoke((MethodInvoker)delegate
            {
                uiGroup.NextReminderLabel.Text = reminderItem.NextReminderTime.ToString("HH:mm:ss");
                TimeSpan remaining = reminderItem.NextReminderTime - DateTime.Now;
                uiGroup.CountdownLabel.Text = remaining.TotalSeconds > 0 ? $"{remaining.Hours:D2}:{remaining.Minutes:D2}:{remaining.Seconds:D2}" : "00:00:00";
            });
        }

        // 添加LogMessage方法，用于记录操作日志
        public void LogMessage(MainForm mainForm, string message)
        {
            string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string logEntry = $"[{timestamp}] {message}";

            _ = mainForm.Invoke((MethodInvoker)delegate
            {
                if (_logTextBox != null)
                {
                    _logTextBox.AppendText(logEntry + Environment.NewLine);
                    _logTextBox.ScrollToCaret();
                }
            });
        }

        // 显示提醒窗口
        public void ShowReminder(MainForm mainForm, bool isTest = false)
        {
            // 这个方法保留用于向后兼容
            if (ReminderItems.Count > 0)
            {
                ShowReminder(mainForm, isTest, ReminderItems[0].Id);
            }
        }

        // 显示指定提醒项的提醒窗口
        public void ShowReminder(MainForm mainForm, bool isTest, string reminderId)
        {
            ReminderItem? reminderItem = ReminderItems.Find(r => r.Id == reminderId);
            if (reminderItem == null)
            {
                return;
            }

            if (isTest)
            {
                LogMessage(mainForm, $"{reminderItem.Name}测试提醒弹出");
            }
            else
            {
                LogMessage(mainForm, $"{reminderItem.Name}时间到！");
            }

            Form reminderForm = new Form
            {
                Text = reminderItem.Name,
                Size = new Size(350, 280),
                StartPosition = FormStartPosition.CenterScreen,
                FormBorderStyle = FormBorderStyle.FixedDialog,
                MaximizeBox = false,
                MinimizeBox = false,
                TopMost = true
            };

            Label emojiLabel = new Label
            {
                Text = $"🚨 {reminderItem.Name} 🚨",
                Font = new Font("Microsoft YaHei", 14, FontStyle.Bold),
                Location = new Point(80, 20),
                AutoSize = true
            };
            reminderForm.Controls.Add(emojiLabel);

            Label messageLabel = new Label
            {
                Text = reminderItem.Message,
                Font = new Font("Microsoft YaHei", 11),
                Location = new Point(20, 60),
                Size = new Size(310, 60),
                TextAlign = ContentAlignment.MiddleCenter
            };
            reminderForm.Controls.Add(messageLabel);

            // 仅在非测试提醒中显示按钮
            if (!isTest)
            {
                Button nextRoundButton = new Button
                {
                    Text = "开始下一轮提醒",
                    Size = new Size(120, 35),
                    Location = new Point(40, 150)
                };
                nextRoundButton.Click += (s, e) =>
                {
                    reminderItem.NextReminderTime = DateTime.Now.AddMinutes(reminderItem.Interval);

                    // 保存设置
                    SaveReminderSettings();

                    reminderForm.Close();
                    LogMessage(mainForm, $"用户选择开始下一轮{reminderItem.Name}，提醒间隔: {reminderItem.Interval}分钟，下次提醒时间: {reminderItem.NextReminderTime:yyyyMMdd HH:mm:ss}");
                };
                reminderForm.Controls.Add(nextRoundButton);

                Button stopButton = new Button
                {
                    Text = "停止提醒",
                    Size = new Size(100, 35),
                    Location = new Point(180, 150)
                };
                stopButton.Click += (s, e) =>
                {
                    if (reminderItem.IsEnabled)
                    {
                        StopMonitoring(mainForm, reminderId);
                        LogMessage(mainForm, $"用户选择停止{reminderItem.Name}");
                    }
                    else
                    {
                        LogMessage(mainForm, $"{reminderItem.Name}测试提醒已关闭");
                    }
                    reminderForm.Close();
                };
                reminderForm.Controls.Add(stopButton);
            }

            _ = reminderForm.ShowDialog();
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}